from google.appengine.ext import db
from google.appengine.api import users

class Category(db.Model):
   title = db.StringProperty()

class Feed(db.Model):
   title = db.StringProperty()
   url = db.StringProperty()
   source = db.StringProperty()
   category = db.ReferenceProperty(Category)
   weight = db.IntegerProperty()

class FeedContent(db.Model):
   title = db.StringProperty()
   url = db.StringProperty()
   content = db.TextProperty()
   date = db.DateTimeProperty()
   feed = db.ReferenceProperty(Feed)
   hash = db.StringProperty()

class UserCategories(db.Model):
   user = db.UserProperty()
   category = db.ReferenceProperty(Category)

class UserFeeds(db.Model):
   user = db.UserProperty()
   feed = db.ReferenceProperty(Feed)
   date = db.DateTimeProperty()

class UserRatings( db.Model ):
	feedContent = db.ReferenceProperty( FeedContent )
	user = db.UserProperty()
	rate = db.FloatProperty()

class DbLog(db.Model):
   table    = db.StringProperty()
   property = db.StringProperty()
   value    = db.StringProperty()

   # update table property
   # @params table, property, value string	
   def update(self, table, property, value):
       	query = self.all().filter("table =", table).filter("property =", property)
        results = query.fetch(10);
	if (len(results) == 0):
	    self.table = table
	    self.property = property	
	    self.put()
	    print "put"	
	else:
	    if value == "+1":
		if results[0].value is None: 
		    results[0].value = "1"
		else:
	            results[0].value = str(int(results[0].value) + 1)
	    elif value == "-1":
		if results[0].value is None:
		    results[0].value = "0"
		else:
	            results[0].value = str(int(results[0].value) - 1)
	    else:
	        results[0].value = str(value)

            results[0].put()
	    return True

   # get total property value
   # @param table string
   def getTotal(self, table):
	results = self.all().filter("table =", table).filter("property = ", "total")

	if results.count() > 0:
		return results[0].value	
	else:
		return None


